package com.springboot.demo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.JSONToken;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.demo.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.*;

/**
 * @author wubc683
 * @desc
 * @date 2021-10-16 14:10
 */
@Slf4j
public class StringJsonUtils {
    /**
     * jsonstring 转换成map
     *
     * @param jsonString
     * @return
     * @throws Exception
     */

    public static Map<String, Object> jsonStringToMap(String jsonString) {
        Map<String, Object> map = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        for (Object k : jsonObject.keySet()) {
            Object o = jsonObject.get(k);
            if (o instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<>();
                Boolean isArrayType = false;
                for (Object obj : (JSONArray) o) {
                    if (obj == null) {
                        list.add(null);
                    } else {
                        if (obj instanceof JSONObject || obj instanceof JSONArray) {
                            list.add(jsonStringToMap(obj.toString()));
                        } else {
//                            List<String> l = new ArrayList<>();
//                            for (Object obj1 : (JSONArray) o) {
//                                if (obj1 != null) {
//                                    l.add(obj1.toString().trim());
//                                } else {
//                                    l.add(String.valueOf((Object) null));
//                                }
//                            }
//                            map.put(k.toString(), l.toString());
                            // 如果内层是数组["11","22","33"...],不解析
                            map.put(k.toString(), o);
                            isArrayType = true;
                            break;
                        }
                    }

                }
                if (!isArrayType) {
                    map.put(k.toString(), list);
                }
            } else if (o instanceof JSONObject) {
                // 如果内层是json对象的话，继续解析
                map.put(k.toString(), jsonStringToMap(o.toString()));
            } else {
                // 如果内层是普通对象的话，直接放入map中
                if (o instanceof String) {
                    map.put(k.toString(), o.toString().trim());
                } else {
                    map.put(k.toString(), o);
                }
            }
        }
        return map;
    }
}
